﻿using UnityEngine;
using System.Collections;
using System;

public class TankShooting : MonoBehaviour {

    public int PlayerNumber = 1;
    public Rigidbody Shell;
    public Transform FireTransform;
    public float MinLaunchForce = 5f;
    public float MaxLaunchForce = 10f;
    public float MaxChargeTime = 0.75f;
    public float FireRate = 0.5f;
    public Animator m_animator;
    public ParticleSystem m_fireEffect;
    public IJoyStick joyStick;

    private float _curLaunchForce;
    private float _chargeSpeed;
    private bool _fired;
    private DateTime  _lastFireMillisecond;

    private void OnEnable()
    {
        _curLaunchForce = MinLaunchForce;
    }
    
	void Start () {
        _chargeSpeed = (MaxLaunchForce - MinLaunchForce) / MaxChargeTime;

        //m_fireEffect = Instantiate(m_fireEffect);
    }

    void Update () {
        bool isFireDown = false;
        bool isFirePressing = false;
        bool isFireUp = false;

        if(joyStick!=null)
        {
            isFireDown = joyStick.isFireDown;
            isFirePressing = joyStick.isFirePressing;
            isFireUp = joyStick.isFireUp;
        }

        if (_curLaunchForce >= MaxLaunchForce && !_fired)
        {
            _curLaunchForce = MaxLaunchForce;
            Fire();
        }
        else if (isFireDown)
        {
            _fired = false;
            _curLaunchForce = MinLaunchForce;
        }
        else if (isFirePressing && !_fired)
        {
            _curLaunchForce += _chargeSpeed * Time.deltaTime;
        }
        else if (isFireUp && !_fired)
        {
            Fire();
        }
    }

    public void Fire()
    {
        DateTime curTime = DateTime.Now;
        TimeSpan ts = (curTime - _lastFireMillisecond);
        long interval = Convert.ToInt64(ts.TotalMilliseconds);
        if (interval >= FireRate*1000)
        {
            _lastFireMillisecond = curTime;
            //go on
        }else
        {
            return;
        }

        MakeFireEffect();

        _fired = true;
        Rigidbody shellInstance = Instantiate(Shell, 
            FireTransform.position, FireTransform.rotation) as Rigidbody;

        shellInstance.velocity = _curLaunchForce * FireTransform.forward;

        _curLaunchForce = MinLaunchForce;

    }

    private void MakeFireEffect()
    {
        m_fireEffect.transform.position = FireTransform.position;
        m_fireEffect.Stop();
        m_fireEffect.Play();

        m_animator.SetTrigger("triggerShoot");
    }
}
